<template>
  <div
    id="drag"
    @touchstart.prevent="touchStartHandle"
    @touchmove.prevent="touchMoveHandle"
    @touchend.prevent="touchEndHandle"
  >
    <slot></slot>
  </div>
</template>
<script>
/* 获取鼠标在盒子的差值 */
var dx, dy;
/* 获取设备宽度 */
var screenWidth = window.screen.width;
var screenHeight = window.screen.height;
export default {
  name: "drag",
  data() {
    return {
      flags: false,
      position: {
        left: "",
        top: "",
      },
    };
  },
  mounted() {
    window.addEventListener("resize", this.windowSizeHandle);
  },
  methods: {
    touchStartHandle(event) {
      //   console.log(event);
      /* 获取当前鼠标在盒子内地位置 */
      this.flags = true;
      let touchs = event.touches[0];
      /* 鼠标在盒子X轴的位置 */
      let x = touchs.clientX;
      /* 获取鼠标在盒子y轴的位置 */
      let y = touchs.clientY;
      //   console.log(x, y);
      /* 获取盒子Y轴的边偏移 */
      let offsetY = touchs.target.offsetTop;
      let offsetX = touchs.target.offsetLeft;
      dx = x - offsetX;
      dy = y - offsetY;
      //   console.log(dx, dy);
      /*  */
    },
    touchMoveHandle(e) {
      if (this.flags) {
        let touchs = e.touches[0];
        /* 获取当前鼠标移动的Y轴位置 */
        let cY = touchs.clientY;
        let cX = touchs.clientX;
        this.position.left = cX - dx;
        this.position.top = cY - dy;
        if (this.position.left <= 0) {
          this.position.left = 0;
        } else if (
          this.position.left >=
          screenWidth - touchs.target.clientWidth
        ) {
          this.position.left = screenWidth - touchs.target.clientWidth;
        }
        if (this.position.top <= 0) {
          this.position.top = 0;
        } else if (
          this.position.top >=
          screenHeight - touchs.target.clientHeight
        ) {
          this.position.top = screenHeight - touchs.target.clientHeight;
        }
        let drag=document.getElementById('drag')
        console.log(e)
        // e.target.style.top = this.position.top + "px";
        // e.target.style.left = this.position.left + "px";
      }
    },
    touchEndHandle() {
      //   window.removeEventListener("mousemove", this.windowMoveHandle);
      this.flags = false;
    },
    windowSizeHandle(e) {
      screenWidth = e.target.outerWidth;
      screenHeight = e.target.outerHeight;
    },
  },
  computed: {},
  watch: {},
  destroyed() {
    window.removeEventListener("resize", this.windowSizeHandle);
  },
};
</script>
<style lang="scss" scoped>
</style>